<template>
  <t-adaptive-page
    class="menu_mange"
    tableTitle="订单列表"
    ref="TAdaptivePageDemo"
    isCopy
    :table="state.table"
    :columns="state.table.columns"
    :opts="opts"
    isExpansion
    columnSetting
    :isTTableSelfFilling="false"
    isShowWidthSize
    :widthSize="4"
    @size-change="handlesSizeChange"
    @page-change="handlesCurrentChange"
    @radio-change="selectionChange"
    @submit="conditionEnter"
  >
    <template #nickName="{ scope }">
      <div>{{ scope.row.nickName }}</div>
    </template>
    <template #SalesCode="{ scope }">
      <div>
        <el-link
            link
            @click="handleUpdate(scope.row)"
            type="primary"
        >{{ scope.row.SalesCode }}</el-link>
      </div>
    </template>

    <template #toolbar>
      <div v-if="state.selectedRow">
        <el-button type="primary" link @click="handleUpdate(state.selectedRow)" >详情</el-button>
<!--        <el-button type="primary" link @click="handleCheck(state.selectedRow)" v-if="['自由'].includes(state.selectedRow.StateID) && checkPermission('审核', state.roleList)">审核</el-button>-->
<!--        <el-button type="danger" link @click="handleDelete(state.selectedRow)" v-if="['自由'].includes(state.selectedRow.StateID) && checkPermission('删除', state.roleList)">删除</el-button>-->
      </div>

      <div v-else style="color:red">
        选择数据后显示操作按钮
      </div>
    </template>

    <template #ddate="{scope}">
      <el-text type="primary">{{ parseTime(scope.row.ddate, '{y}-{m}-{d}' ) }}</el-text>
    </template>
    <template #footerBtn>
<!--      <el-button type="danger" @click="addHandle()">新增</el-button>-->
      <!--      <el-button type="danger" @click="importHandle()">导入</el-button>-->
      <!--      <el-button type="danger" @click="deleteHandles" :disabled="!state.ids.length">删除</el-button>-->

      <el-button type="primary" @click="TAdaptivePageDemo.TQueryConditionPage.checkHandle()"
        >查询</el-button
      >
      <el-button type="danger" @click="TAdaptivePageDemo.TQueryConditionPage.resetHandle()"
        >重置</el-button
      >
    </template>


  </t-adaptive-page>
  <!--  新增 / 修改-->
  <el-dialog
      :title="state.addDialog.title"
      width="95%"
      v-model="state.addDialog.visible"
      draggable
      top="10px"
      :close-on-click-modal="false"
  >
    <div>
      <el-form :model="state.addDialog.formData" :rules="state.addDialog.rules" ref="formRef">
        <!--   第一行   -->
        <el-divider content-position="left">基础信息</el-divider>
        <el-row :gutter="10">
          <el-col :span="6">
            <el-form-item label="合同" prop="ContractNo">
              <el-select
                  v-model="state.addDialog.formData.ContractNo"
                  filterable
                  remote
                  reserve-keyword
                  @change="updateContarctInfo"
                  placeholder="请选择合同号"
                  remote-show-suffix
              >
                <el-option
                    v-for="item in cubasdoc.contractList"
                    :key="item.ContractNum"
                    :label="item.ProjectName"
                    :value="item.ContractNum"
                >
                  <span style="float: left">{{ item.ProjectName }}</span>
                  <span
                      style="float: right; color: var(--el-text-color-secondary); font-size: 13px"
                  >【{{ item.ContractNum }}】</span
                  >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="是否补录" prop="repair">
              <el-select
                  v-model="state.addDialog.formData.repair"
                  filterable
                  clearable
                  remote
                  reserve-keyword
                  placeholder="请选择是否补录"
                  remote-show-suffix
              >
                <el-option label="是" value="是"></el-option>
                <el-option label="否" value="否"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="销售类型" prop="SalesType">
              <el-select
                  v-model="state.addDialog.formData.SalesType"
                  filterable
                  clearable
                  remote
                  reserve-keyword
                  placeholder="请选择合同类型"
                  remote-show-suffix
              >
                <el-option label="分期收款" value="分期收款"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="销售订单号" prop="SalesCode">
              <el-input
                  v-model="state.addDialog.formData.SalesCode"
                  placeholder="请输入销售订单号"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="交易类型" prop="TranType">
              <el-select
                  v-model="state.addDialog.formData.TranType"
                  filterable
                  clearable
                  remote
                  reserve-keyword
                  placeholder="请选择交易类型"
                  remote-show-suffix
              >
                <el-option label="分期收款" value="分期收款"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="单据日期" prop="ddate">
              <el-date-picker
                  v-model="state.addDialog.formData.ddate"
                  style="width: 100%"
                  format="YYYY-MM-DD "
                  value-format="YYYY-MM-DD"
                  type="datetime"
                  clearable
                  placeholder="选择日期"
              />
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="业务员" prop="salesman">
              <el-select
                  @change="changeSalesman"
                  v-model="state.addDialog.formData.salesman"
                  filterable
                  clearable
                  remote
                  reserve-keyword
                  placeholder="请选择业务员"
                  remote-show-suffix
              >
                <el-option
                    :label="item.cPsn_Name"
                    :value="item.cPsn_Num"
                    v-for="(item, index) in state.userList"
                    :key="index"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="部门" prop="cDepName">
              <el-input
                  v-model="state.addDialog.formData.cDepName"
                  disabled
                  placeholder="请输入部门"
              />
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="客户" prop="cCusCode">
              <el-select
                  v-model="state.addDialog.formData.cCusCode"
                  filterable
                  remote
                  reserve-keyword
                  placeholder="请选择客户"
                  :remote-method="cnvbasdocMethod"
                  :loading="state.loading"
                  @change="changeCustCode"
                  remote-show-suffix
              >
                <el-option
                    v-for="item in cusoptions"
                    :key="item.cCusCode"
                    :label="item.ccusabbname"
                    :value="item.cCusCode"
                >
                  <span style="float: left">{{ item.ccusabbname }}</span>
                  <span
                      style="float: right; color: var(--el-text-color-secondary); font-size: 13px"
                  >【{{ item.cCusCode }}】</span
                  >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="地址" prop="address">
              <el-input
                  v-model="state.addDialog.formData.address"
                  placeholder="请输入地址"
              ></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="税率" prop="taxrate">
              <el-input
                  v-model="state.addDialog.formData.taxrate"
                  type="number"
                  placeholder="请输入税率"
              ></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="汇率" prop="ExchangeRate">
              <el-input
                  v-model="state.addDialog.formData.ExchangeRate"
                  type="number"
                  placeholder="请输入汇率"
              ></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="客户联系人" prop="contacts">
              <el-input
                  v-model="state.addDialog.formData.contacts"
                  placeholder="请输入客户联系人"
              ></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="客户联系人手机" prop="Telephone">
              <el-input
                  v-model="state.addDialog.formData.Telephone"
                  placeholder="请输入客户联系人手机"
              ></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="发货方式" prop="DeliveryMethod">
              <el-input
                  v-model="state.addDialog.formData.DeliveryMethod"
                  placeholder="请输入发货方式"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="包装方式" prop="PackingMethod">
              <el-input
                  v-model="state.addDialog.formData.PackingMethod"
                  placeholder="请输入包装方式"
              ></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="备注" prop="remarks">
              <el-input
                  v-model="state.addDialog.formData.remarks"
                  type="textarea"
                  :rows="3"
                  placeholder="请输入备注"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-divider content-position="left"></el-divider>
        <el-descriptions v-if="false" class="margin-top" title="审计信息" :column="3">
          <el-descriptions-item label="单据状态">{{
              state.addDialog.formData.StateID
            }}</el-descriptions-item>
          <el-descriptions-item label="正在变更">{{
              state.addDialog.formData.change
            }}</el-descriptions-item>
          <el-descriptions-item label="同步U8">{{
              state.addDialog.formData.SFU8
            }}</el-descriptions-item>
          <el-descriptions-item label="发货关闭">{{
              state.addDialog.formData.ShipClosed
            }}</el-descriptions-item>

          <el-descriptions-item label="订单关闭">{{
              state.addDialog.formData.OrderClosing
            }}</el-descriptions-item>
          <el-descriptions-item label="制单人">{{
              state.addDialog.formData.Preparer
            }}</el-descriptions-item>
          <el-descriptions-item label="制单时间">{{
              state.addDialog.formData.Pdate
            }}</el-descriptions-item>

          <el-descriptions-item label="修改人">{{
              state.addDialog.formData.Modified
            }}</el-descriptions-item>

          <el-descriptions-item label="修改时间">{{
              state.addDialog.formData.Mdate
            }}</el-descriptions-item>
        </el-descriptions>
      </el-form>
      <el-row>
        <el-col :span="24">
          <div>
            <t-table
                title="明细"
                :table="state.table_d"
                :columns="state.table_d.columns"
                :isShowPagination="false"
                ref="singleEditTSelectTable"
                :listTypeInfo="state.listTypeInfo"
                @handleEvent="handleEvent"
                @validateError="validateError"
            >
              <template #toolbar>
                <el-button type="primary" @click="addOneTable">新增一行</el-button>
              </template>
              <!-- 自定义单元格编辑组件(多选下拉选择) -->
              <template #editHobby="{ scope }">
                <el-select
                    v-if="state.addDialog.formData.cCusCode"
                    v-model="scope.row[scope.column.property]"
                    filterable
                    remote
                    reserve-keyword
                    placeholder="请输入存货名称或编码"
                    remote-show-suffix
                    :remote-method="remoteMethod"
                    :loading="state.loading"
                    @change="e => updateInv(e, scope.row)"
                    style="width: 100%"
                >
                  <el-option
                      v-for="item in state.options"
                      :key="item.id"
                      :label="item.id"
                      :value="item.id"
                  >
                    <span style="float: left">{{ item.name }}</span>
                    <span
                        style="float: right; color: var(--el-text-color-secondary); font-size: 13px"
                    >
                        {{ item.id }}
                      </span>
                  </el-option>
                </el-select>
              </template>
            </t-table>
          </div>
        </el-col>
      </el-row>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="closeDialog">取 消</el-button>
        <el-button type="primary" @click="submitForm" :loading="state.loading">确 定</el-button>
      </div>
    </template>
  </el-dialog>
  <!--  变更-->
  <el-dialog
      title="变更"
      width="95%"
      v-model="state.update.visible"
      draggable
      top="10px"
      :close-on-click-modal="false"
  >
    <div>
      <el-form :model="state.update.formData" :rules="state.update.rules" ref="updateformRef">
        <!--   第一行   -->
        <el-divider content-position="left">基础信息</el-divider>
        <el-row :gutter="10">
          <el-col :span="6">
            <el-form-item label="合同" prop="ContractNo">
              <el-select
                  v-model="state.update.formData.ContractNo"
                  filterable
                  remote
                  disabled
                  reserve-keyword
                  @change="updateContarctInfo"
                  placeholder="请选择合同号"
                  remote-show-suffix
              >
                <el-option
                    v-for="item in cubasdoc.contractList"
                    :key="item.ContractNum"
                    :label="item.ProjectName"
                    :value="item.ContractNum"
                >
                  <span style="float: left">{{ item.ProjectName }}</span>
                  <span
                      style="float: right; color: var(--el-text-color-secondary); font-size: 13px"
                  >【{{ item.ContractNum }}】</span
                  >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="是否补录" prop="repair">
              <el-select
                  v-model="state.update.formData.repair"
                  filterable
                  clearable
                  disabled
                  remote
                  reserve-keyword
                  placeholder="请选择是否补录"
                  remote-show-suffix
              >
                <el-option label="是" value="是"></el-option>
                <el-option label="否" value="否"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="销售类型" prop="SalesType">
              <el-select
                  v-model="state.update.formData.SalesType"
                  filterable
                  disabled
                  clearable
                  remote
                  reserve-keyword
                  placeholder="请选择合同类型"
                  remote-show-suffix
              >
                <el-option label="分期收款" value="分期收款"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="销售订单号" prop="SalesCode">
              <el-input
                  v-model="state.update.formData.SalesCode"
                  disabled
                  placeholder="请输入销售订单号"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="交易类型" prop="TranType">
              <el-select
                  v-model="state.update.formData.TranType"
                  filterable
                  clearable
                  remote
                  disabled
                  reserve-keyword
                  placeholder="请选择交易类型"
                  remote-show-suffix
              >
                <el-option label="分期收款" value="分期收款"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="单据日期" prop="ddate">
              <el-date-picker
                  v-model="state.update.formData.ddate"
                  disabled
                  style="width: 100%"
                  format="YYYY-MM-DD "
                  value-format="YYYY-MM-DD"
                  type="datetime"
                  clearable
                  placeholder="选择日期"
              />
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="业务员" prop="salesman">
              <el-select
                  disabled
                  @change="changeSalesman"
                  v-model="state.update.formData.salesman"
                  filterable
                  clearable
                  remote
                  reserve-keyword
                  placeholder="请选择业务员"
                  remote-show-suffix
              >
                <el-option
                    :label="item.cPsn_Name"
                    :value="item.cPsn_Num"
                    v-for="(item, index) in state.userList"
                    :key="index"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="部门" prop="cDepName">
              <el-input
                  v-model="state.update.formData.cDepName"
                  disabled
                  placeholder="请输入部门"
              />
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="客户" prop="cCusCode">
              <el-select
                  v-model="state.update.formData.cCusCode"
                  filterable
                  remote
                  disabled
                  reserve-keyword
                  placeholder="请选择客户"
                  :remote-method="cnvbasdocMethod"
                  :loading="state.loading"
                  @change="changeCustCode"
                  remote-show-suffix
              >
                <el-option
                    v-for="item in cusoptions"
                    :key="item.cCusCode"
                    :label="item.ccusabbname"
                    :value="item.cCusCode"
                >
                  <span style="float: left">{{ item.ccusabbname }}</span>
                  <span
                      style="float: right; color: var(--el-text-color-secondary); font-size: 13px"
                  >【{{ item.cCusCode }}】</span
                  >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="地址" prop="address">
              <el-input
                  disabled
                  v-model="state.update.formData.address"
                  placeholder="请输入地址"
              ></el-input>
            </el-form-item>
          </el-col>

          <!--            <el-col :span="6">-->
          <!--              <el-form-item label="税率" prop="taxrate">-->
          <!--                <el-input-->
          <!--                  disabled-->
          <!--                  v-model="state.update.formData.taxrate"-->
          <!--                  type="number"-->
          <!--                  placeholder="请输入税率"-->
          <!--                ></el-input>-->
          <!--              </el-form-item>-->
          <!--            </el-col>-->

          <!--            <el-col :span="6">-->
          <!--              <el-form-item label="汇率" prop="ExchangeRate">-->
          <!--                <el-input-->
          <!--                  disabled-->
          <!--                  v-model="state.update.formData.ExchangeRate"-->
          <!--                  type="number"-->
          <!--                  placeholder="请输入汇率"-->
          <!--                ></el-input>-->
          <!--              </el-form-item>-->
          <!--            </el-col>-->

          <el-col :span="6">
            <el-form-item label="客户联系人" prop="contacts">
              <el-input
                  disabled
                  v-model="state.update.formData.contacts"
                  placeholder="请输入客户联系人"
              ></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="客户联系人手机" prop="Telephone">
              <el-input
                  disabled
                  v-model="state.update.formData.Telephone"
                  placeholder="请输入客户联系人手机"
              ></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="发货方式" prop="DeliveryMethod">
              <el-input
                  disabled
                  v-model="state.update.formData.DeliveryMethod"
                  placeholder="请输入发货方式"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="包装方式" prop="PackingMethod">
              <el-input
                  disabled
                  v-model="state.update.formData.PackingMethod"
                  placeholder="请输入包装方式"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="是否订单关闭" prop="OrderClosing">
              <el-select
                  v-model="state.update.formData.OrderClosing"
                  filterable
                  clearable
                  disabled
                  remote
                  reserve-keyword
                  placeholder="请选择是否关闭"
                  remote-show-suffix
              >
                <el-option label="是" value="是"></el-option>
                <el-option label="否" value="否"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注" prop="remarks">
              <el-input
                  disabled
                  v-model="state.update.formData.remarks"
                  type="textarea"
                  :rows="3"
                  placeholder="请输入备注"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-divider content-position="left"></el-divider>
        <el-descriptions v-if="true" class="margin-top" title="审计信息" :column="3">

          <el-descriptions-item label="制单人:">{{
              state.update.formData.Preparer
            }}</el-descriptions-item>
          <el-descriptions-item label="制单时间:">{{
              state.update.formData.Pdate
            }}</el-descriptions-item>
          <el-descriptions-item label="正在变更">{{
              state.addDialog.formData.change
            }}</el-descriptions-item>
        </el-descriptions>
      </el-form>
      <el-row>
        <el-col :span="24">
          <div >
            <t-table
                title="明细"
                height="300"
                :table="state.table_u"
                :columns="state.table_u.columns"
                :isShowPagination="false"
                ref="singleUpdateTSelectTable"
                :listTypeInfo="state.listTypeInfo"
                @handleEvent="handleEvent"
                @validateError="validateError"
            >

              <template #Xingguan="{ scope }">
                <el-select
                    @change="(e)=>updateChangeContent(e,scope.column.property,scope)"
                    v-model="scope.row[scope.column.property]"
                    filterable
                    clearable
                    remote
                    reserve-keyword
                    placeholder="请选择是否关闭"
                    remote-show-suffix
                >
                  <el-option label="是" value="是"></el-option>
                  <el-option label="否" value="否"></el-option>
                </el-select>
              </template>

              <!-- 自定义单元格编辑组件(多选下拉选择) -->
              <template #editHobby="{ scope }">
                <el-select
                    v-if="state.addDialog.formData.cCusCode"
                    v-model="scope.row[scope.column.property]"
                    filterable
                    remote
                    reserve-keyword
                    placeholder="请输入存货名称或编码"
                    remote-show-suffix
                    :remote-method="remoteMethod"
                    :loading="state.loading"
                    @change="e => updateInv(e, scope.row)"
                    style="width: 100%"
                >
                  <el-option
                      v-for="item in state.options"
                      :key="item.id"
                      :label="item.id"
                      :value="item.id"
                  >
                    <span style="float: left">{{ item.name }}</span>
                    <span
                        style="float: right; color: var(--el-text-color-secondary); font-size: 13px"
                    >
                        {{ item.id }}
                      </span>
                  </el-option>
                </el-select>
              </template>
            </t-table>
          </div>
        </el-col>
      </el-row>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="closeDialog">取 消</el-button>
        <el-button type="primary" @click="submituUpdateForm" :loading="state.loading">确 定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="tsx" name="selection">
import { computed, onMounted, reactive, ref, toRefs } from 'vue'
import { debounce, parseTime,dateDiff,checkPermission } from '@/utils/util'
import { cubasdocStore } from '@/stores/modules/cubasdoc'
import { getContractInfo, getContractList, findbaseBasicManage, findBoxData,userRole } from '@/api/base'
import { salesOrderAdd, salesOrderChangeList,salesChangeOrderCheck, ComboBoxDataList,salesOrderChangeListDetails,salesOrderChangeDelete,salesOrderCheck,salesOrderUnCheck,salesOrderClose,SalesChangeOrder } from '@/api/sale_order'
import { ElMessage, ElMessageBox } from 'element-plus'

// 获取ref
const TAdaptivePageDemo: any = ref(null)
const handleDelete = async (row: any) => {

  ElMessageBox.confirm('此操作将删除该变更单, 是否继续?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(async () => {
      let { code,news } = await salesOrderChangeDelete({ ID: row.Sid })
      if (code===1) {
        ElNotification.success({
          title: '提示',
          message: news,
          offset: 200,
        })
        await getData()
      }else {
        ElNotification.error({
          title: '提示',
          message: '删除失败，'+news,
          offset: 200,
        })
      }
    })
}


const handleClose = async (row: any) => {
  ElMessageBox.prompt('请输入关闭原因', '提示', {
    confirmButtonText: '提交',
    cancelButtonText: '取消',
  })
    .then(async ({ value }) => {
      let { code, news } = await salesOrderClose({ Sid: row.Sid, news: '' })
      if (code === 1) {
        ElNotification.success({
          title: '提示',
          message: news,
          offset: 200,
        })
        await getData()
      } else {
        ElNotification.error({
          title: '提示',
          message: '关闭失败，' + news,
          offset: 200,
        })
      }
    })
    .catch(() => {
    })
}



const handleUnCheck = async (row: any) => {
  let { code,news } = await salesOrderUnCheck({ Sid: row.Sid })
  if (code==1) {
    ElNotification.success({
      title: '提示',
      message: '弃审成功',
      offset: 200,
    })
    await getData()
  }else {
    ElNotification.error({
      title: '提示',
      message: '弃审失败，'+news,
      offset: 200,
    })
  }
}

const handleCheck = async (row: any) => {
  let { code,news } = await salesChangeOrderCheck({ Sid: row.Sid+',' })
  if (code==1) {
    ElNotification.warning({
      title: '提示',
      message: news,
      offset: 200,
    })
    await getData()
  }else {
    ElNotification.error({
      title: '提示',
      message: '审核失败，'+news,
      offset: 200,
    })
  }
}

// 选择复选框
const selectionChange = (val: any) => {

  state.selectedRow = val
}

const editDel = (item, index, row) => {
  //
  row.splice(index, 1)

}


const handerEdit = async (item) => {

  //选择本条数据
  state.addDialog.formData = item
  //查询详情赋值给表格
  let queryData = {
    table: 'SalesOrderView',
    selectvalue: 'undefined',
    value: 'undefined',
    WF: '',
    Sid: item.Sid+",",
  }
  let axiosResponse = await salesOrderChangeListDetails(queryData)

  if (axiosResponse.Rows.length > 0){
    state.table_d.data = axiosResponse.Rows
    state.addDialog.formData.ContractNo = axiosResponse.Rows[0].ContractNo
  }
  state.addDialog.visible = true
}

const handleUpdate = async (item) => {
  //选择本条数据
  state.update.formData = item
  //查询详情赋值给表格
  let queryData = {
    table: 'SalesChangeOrderView',
    Sid: item.Sid,
  }
  let axiosResponse = await salesOrderChangeListDetails(queryData)

  if (axiosResponse.Rows.length > 0) {
    state.table_u.data = axiosResponse.Rows.map((item) => {
      //深度拷贝
      let completeDate = item.completeDate
      return {
        ...item,
        Yquantity: item.quantity,//原数量
        UnitPrice: item.iunitprice,//原单价
        YcompleteDate:completeDate,
      }
    })
    state.update.formData.ContractNo = axiosResponse.Rows[0].ContractNo
  }
  state.update.visible = true
}

// 取消选中
const cancelSelect = () => {

  if (state.ids.length > 0) {

    // 方式一
    TAdaptivePageDemo.value.clearSelection()
    // 方式二（TTablePage ref）
    // TAdaptivePageDemo.value.TTablePage.clearSelection()
  }
}
const state: any = reactive({
  selectedRow:null,
  roleList:[],
  ids: [],
  invOptions: [],
  height: 400,
  queryData: {
  },
  table: {
    border: true,
    firstColumn: { type: 'radio', fixed: true },
    currentPage: 1,
    pageSize: 20,
    total: 0,
    // 接口返回数据
    data: [],
    // 表头数据
    columns: [
      { prop: 'TranType', label: '销售类别',width: 100 },
      { prop: 'ccode', label: '变更单号',width: 140,fixed: 'left', },
      { prop: 'SalesCode', label: '销售订单号',width: 150,fixed: 'left' ,slotName: 'SalesCode' },
      { prop: 'ddate', label: '制单日期',slotName: 'ddate',width: 150},
      { prop: 'StateID', label: '单据状态',width: 100 },
      { prop: 'cDepName', label: '部门',width: 120 },
       { prop: 'salesman', label: '业务员编码',width: 100 },
      { prop: 'cPsn_Name', label: '业务员' },
      { prop: 'cCusCode', label: '客户编码',width: 90 },
      { prop: 'cCusName', label: '客户名称',width: 190 },
      { prop: 'OrderClosing', label: '是否关闭',width: 100 },
      { prop: 'remarks', label: '备注',showOverflowTooltip: true },
      { prop: 'Preparer', label: '制单人' },
      { prop: 'Pdate', label: '制单时间',width: 150 },
    ],
  },
  addDialog: {
    title: '新增',
    visible: false,
    loading: false,
    formData: {
      ddate: parseTime(new Date(), '{y}-{m}-{d}'),
      // BodyJson:[],
      taxrate: 13,
      repair: '否',
      SalesType: '分期付款',
      TranType: '分期付款',
      salesman: '101',
      cDepName: '推广服务部',
      depcode: '05',
      contacts: '王晓峰',
      Telephone: '13323334545',
      DeliveryMethod: '快递',
      PackingMethod: '自备包装',
      remarks: '客户要求私密发货',
      ExchangeRate: 6.5,
      Pdate: parseTime(new Date(), '{y}/{m}/{d} {h}:{i}:{s}'),
      Preparer: '邹涛',
      change: '否',
      StateID: '自由',
    },
    rules: {
      cCusCode: [{ required: true, message: '请选择客户', trigger: 'change' }],
      ContractNo: [{ required: true, message: '请选择合同号', trigger: 'blur' }],
      repair: [{ required: true, message: '请选择是否补录', trigger: 'change' }],
      SalesType: [{ required: true, message: '请选择销售类型', trigger: 'change' }],
      // SalesCode: [{ required: true, message: "请输入销售订单号", trigger: "blur" }],
      TranType: [{ required: true, message: '请选择交易类型', trigger: 'change' }],
      ddate: [{ required: true, message: '请选择单据时间', trigger: 'change' }],
      salesman: [{ required: true, message: '请选择业务员', trigger: 'change' }],

      taxrate: [{ required: true, message: '请输入税率', trigger: 'blur' }],
      ExchangeRate: [{ required: true, message: '请输入汇率', trigger: 'blur' }]
    }
  },
  table_d: {
    rules: {},
    firstColumn: { type: 'index', label: '序号', props: 'LineNum' }, // 显示序列号
    data: [],
    columns: [
      {
        prop: 'cInvCode',
        label: '存货编码',
        placeholder: '请选择存货',
        minWidth: '120',
        canEdit: true,
        headerRequired: true,
        configEdit: {
          label: '存货编码',
          type: 'select-arr',
          editSlotName: 'editHobby',
          rules: { required: true, message: '请输入存货编码', trigger: 'change' },
          editComponent: 'el-select'
        }
      },
      {
        prop: 'cInvName',
        label: '存货名称',
        minWidth: '200',
        headerRequired: true,
        canEdit: true,
        configEdit: {
          label: '存货名称',
          type: 'input',
          rules: { required: true, message: '请输入存货名称', trigger: 'change' },
          editComponent: 'el-input'
        }
      },
      {
        prop: 'cInvStd',
        minWidth: '120',
        label: '规格型号',
        canEdit: true,
        configEdit: {
          label: '规格型号',
          type: 'input',
          editComponent: 'el-input'
        }
      },

      {
        prop: 'cInvCodeK',
        minWidth: '120',
        label: '客户存货编码',
        headerRequired: true,
        canEdit: true,
        configEdit: {
          label: '客户存货编码',
          type: 'input',
          rules: { required: true, message: '请输入客户存货编码', trigger: 'blur' },
          editComponent: 'el-input'
        }
      },

      {
        prop: 'cInvNameK',
        minWidth: '120',
        label: '客户存货名称',
        headerRequired: true,
        canEdit: true,
        configEdit: {
          label: '客户存货名称',
          type: 'input',
          rules: { required: true, message: '请输入客户存货名称', trigger: 'blur' },
          editComponent: 'el-input'
        }
      },
      {
        prop: 'cInvStdK',
        minWidth: '160',
        label: '客户存货规格型号',
        headerRequired: true,
        canEdit: true,
        configEdit: {
          label: '客户存货规格型号',
          type: 'input',
          editComponent: 'el-input'
        }
      },
      {
        prop: 'UnitPrice',
        label: '单价',
        minWidth: '180',
        headerRequired: true,
        canEdit: true,
        configEdit: {
          label: '单价',
          type: 'inputNumber',
          bind: { min: 0 },
          editComponent: 'el-input-number',
          rules: { required: true, message: '请输入单价', trigger: 'blur' },
          eventHandle: {
            change: ({ val, prop, scope }) => numChange(val, prop, scope)
          }
        }
      },
      {
        prop: 'quantity',
        label: '数量',
        minWidth: '180',
        canEdit: true,
        headerRequired: true,
        configEdit: {
          label: '数量',
          type: 'inputNumber',
          bind: { min: 0 },
          rules: { required: true, message: '请输入数量', trigger: 'blur' },
          editComponent: 'el-input-number',
          eventHandle: {
            change: ({ val, prop, scope }) => numChange(val, prop, scope)
          }
        }
      },
      {
        prop: 'taxRate',
        label: '税率',
        minWidth: '180',
        headerRequired: true,
        canEdit: true,
        configEdit: {
          label: '税率',
          type: 'inputNumber',
          bind: { min: 0 },
          rules: { required: true, message: '请输入税率', trigger: 'blur' },
          editComponent: 'el-input-number',
          eventHandle: {
            change: ({ val, prop, scope }) => numChange(val, prop, scope)
          }
        }
      },

      {
        prop: 'deliver',
        minWidth: '160',
        label: '初始预发货日期',
        canEdit: true,
        headerRequired: true,
        configEdit: {
          label: '初始预发货日期',
          type: 'date',
          rules: { required: true, message: '请选择初始预发货日期', trigger: 'blur' },
          editComponent: 'el-date-picker'
          // bind: { valueFormat: "yyyy-Mm-dd" }
        }
      },
      {
        prop: 'deliverDate',
        minWidth: '160',
        label: '实际预发货日期',
        canEdit: true,
        headerRequired: true,
        configEdit: {
          label: '实际预发货日期',
          type: 'date',
          rules: { required: true, message: '请选择实际预发货日期', trigger: 'blur' },
          editComponent: 'el-date-picker'
          // bind: { valueFormat: "yyyy-mm-dd" }
        }
      },
      {
        prop: 'Xingguan',
        minWidth: '160',
        label: '是否关闭',
        canEdit: true,
        headerRequired: true,
        configEdit: {
          label: '是否关闭',
          type: 'select-arr',
          editComponent: 'el-select',
          rules: { required: true, message: '请选择是否关闭', trigger: 'blur' },
          list: [
            {
              id: '是',
              name: '是'
            },
            {
              id: '否',
              name: '否'
            }
          ],
          arrLabel: 'name',
          arrKey: 'id',
        },

      },

      {
        prop: 'MOQ',
        minWidth: '160',
        label: '订单MOQ',
        canEdit: true,
        configEdit: {
          label: '订单MOQ',
          type: 'input',
          bind: { min: 0 },
          editComponent: 'el-input'
        }
      },

      {
        prop: 'DeliveryTime',
        minWidth: '160',
        label: '客户停产日期',
        canEdit: true,
        // headerRequired: true,
        configEdit: {
          label: '客户停产日期',
          type: 'date',
          // rules: { required: true, message: "请选择客户停产日期", trigger: "blur" },
          editComponent: 'el-date-picker',
          bind: { valueFormat: 'yyyy-mm-dd' }
        }
      },

      {
        prop: 'MinimumTime',
        minWidth: '160',
        label: '最短交期(天)',
        canEdit: true,
        configEdit: {
          label: '最短交期',
          type: 'input',
          bind: { min: 0 },
          // rules: { required: true, message: "请输入最短交期", trigger: "blur" },
          editComponent: 'el-input',
          eventHandle: {
            change: ({ val, prop, scope }) => numChange(val, prop, scope)
          }
        }
      },

      {
        prop: 'MaterialShutdown',
        minWidth: '160',
        label: '物料停产日期',
        canEdit: true,
        // headerRequired: true,
        configEdit: {
          label: '物料停产日期',
          type: 'date',
          // rules: { required: true, message: "请选择物料停产日期", trigger: "blur" },
          editComponent: 'el-date-picker',
          bind: { valueFormat: 'yyyy-mm-dd' }
        }
      },
      {
        prop: 'SafetyStock',
        minWidth: '180',
        label: '安全库存量',
        // headerRequired: true,
        canEdit: true,
        configEdit: {
          label: '安全库存量',
          type: 'inputNumber',
          bind: { min: 0 },
          // rules: { required: true, message: "请输入安全库存量", trigger: "blur" },
          editComponent: 'el-input-number'
        }
      },
      {
        prop: 'TransitionStatus',
        minWidth: '160',
        label: '转产状态',
        // headerRequired: true,
        canEdit: true,
        configEdit: {
          label: '转产状态',
          type: 'input',
          bind: { min: 0 },
          // rules: { required: true, message: "请输入转产状态", trigger: "blur" },
          editComponent: 'el-input'
        }
      },
      {
        prop: 'makeUp',
        label: '拼板数',
        // headerRequired: true,
        minWidth: '180',
        canEdit: true,
        configEdit: {
          label: '拼板数',
          type: 'inputNumber',
          bind: { min: 0 },
          // rules: { required: true, message: "请输入拼板数", trigger: "blur" },
          editComponent: 'el-input-number'
        }
      },

      {
        prop: 'completeDate',
        minWidth: '160',
        label: '预生产完工日期',
        canEdit: true,
        // headerRequired: true,
        configEdit: {
          label: '预生产完工日期',
          type: 'date',
          // rules: { required: true, message: "请选择预生产完工日期", trigger: "blur" },
          editComponent: 'el-date-picker',
          bind: { valueFormat: 'yyyy-mm-dd' }
        }
      },
      {
        prop: 'cycle',
        minWidth: '180',
        label: '日均产量',
        // headerRequired: true,
        canEdit: true,
        configEdit: {
          label: '日均产量',
          type: 'inputNumber',
          bind: { min: 0 },
          // rules: { required: true, message: "请输入日均产量", trigger: "blur" },
          editComponent: 'el-input-number'
        }
      },
      {
        prop: 'Productivity',
        minWidth: '160',
        label: '产品难度系数',
        // headerRequired: true,
        canEdit: true,
        configEdit: {
          label: '产品难度系数',
          type: 'input',
          bind: { min: 0 },
          // rules: { required: true, message: "请输入产品难度系数", trigger: "blur" },
          editComponent: 'el-input'
        }
      },

      {
        prop: 'ActualCycle',
        minWidth: '160',
        label: '标准产品产能',
        // headerRequired: true,
        canEdit: true,
        configEdit: {
          label: '标准产品产能',
          type: 'input',
          bind: { min: 0 },
          // rules: { required: true, message: "请输入标准产品产能", trigger: "blur" },
          editComponent: 'el-input'
        }
      },
      {
        prop: 'ActualCycleJ',
        minWidth: '160',
        label: '交付日总产能',
        canEdit: true,
        configEdit: {
          label: '交付日总产能',
          type: 'input',
          bind: { min: 0 },
          editComponent: 'el-input'
        }
      },
      {
        prop: 'CustomerOrder',
        minWidth: '160',
        label: '客户订单号',
        // headerRequired: true,
        canEdit: true,
        configEdit: {
          label: '客户订单号',
          type: 'input',
          bind: { min: 0 },
          // rules: { required: true, message: "请输入客户订单号", trigger: "blur" },
          editComponent: 'el-input'
        }
      },
      // {
      //   prop: "Xingguan",
      //   minWidth: "160",
      //   label: "是否行关闭",
      // },
      {
        prop: 'remarks',
        minWidth: '160',
        label: '备注',
        canEdit: true,
        configEdit: {
          label: '备注',
          type: 'input',
          bind: { min: 0 },
          // rules: { required: true, message: "请输入备注", trigger: "blur" },
          editComponent: 'el-input'
        }
      },
      {
        prop: 'ContractID',
        minWidth: '160',
        label: '标的ID',
        canEdit: true,
        configEdit: {
          label: '标的ID',
          type: 'input',
          bind: { min: 0 },
          rules: { required: true, message: '请输入标的ID', trigger: 'blur' },
          editComponent: 'el-input'
        }
      },
      {
        prop: 'ContractNo',
        minWidth: '160',
        label: '合同号',
        canEdit: true,
        configEdit: {
          label: '合同号',
          type: 'input',
          bind: { min: 0 },
          rules: { required: true, message: '请输入合同号', trigger: 'blur' },
          editComponent: 'el-input'
        }
      }
      // {
      //   prop: "upgrade",
      //   minWidth: "140",
      //   label: "无预测下单",
      // },
    ],
    // 表格内操作列
    operator: [
      {
        type: 'danger',
        text: '删除',
        fun: editDel
      }
    ],
    operatorConfig: {
      fixed: 'right'
    }
  },
  userList: [],
  invList: [],
  update:{
    formData:{
      StateID:'自由',
    },
    visble: false,
    rules:[]
  },
  table_u: {
    rules: {},
    firstColumn: { type: 'index', label: '序号', props: 'LineNum' }, // 显示序列号
    data: [],
    columns: [
      {
        prop: 'ChangeContent',
        label: '变更内容',
        minWidth: '120',
      },
      {
        prop: 'quantity',
        label: '数量',
        minWidth: '80',

      },
      {
        prop: 'Yquantity',
        label: '原数量',
        minWidth: '80',
      },
      {
        prop: "Xingguan",
        label: "是否行关闭",
        minWidth: "80",
      },
      {
        prop: 'CustomerOrder',
        minWidth: '110',
        label: '客户订单号',
      },
      {
        prop: 'deliverDate',
        minWidth: '130',
        label: '实际预发货日期',
      },

      {
        prop: 'YdeliverDate',
        minWidth: '160',
        label: '原实际预发货日期',
      },
      {
        prop: 'DateChange',
        minWidth: '160',
        label: '发货日期变化',
      },

      {
        prop: 'cInvCode',
        label: '存货编码',
        placeholder: '请选择存货',
        minWidth: '120',
      },
      {
        prop: 'cInvName',
        label: '存货名称',
        minWidth: '200',
      },
      {
        prop: 'cInvStd',
        minWidth: '120',
        label: '规格型号',
      },

      {
        prop: 'cInvCodeK',
        minWidth: '120',
        label: '客户存货编码',
      },

      {
        prop: 'cInvNameK',
        minWidth: '120',
        label: '客户存货名称',
      },
      {
        prop: 'cInvStdK',
        minWidth: '160',
        label: '客户存货规格型号',
      },
      {
        prop: 'completeDate',
        minWidth: '160',
        label: '预完工日期',
      },
      {
        prop: 'YcompleteDate',
        minWidth: '160',
        label: '原预完工日期',
      },
      {
        prop: 'remarks',
        minWidth: '160',
        label: '备注',
      },
      {
        prop: 'UnitPrice',
        label: '单价',
        minWidth: '180',
      },

      {
        prop: 'taxRate',
        label: '税率',
        minWidth: '180',
      },

    ],
  },
})

const opts = computed(() => {
  return {
    SalesCode: {
      label: '销售订单号',
      comp: 'el-input'
    },
    ccode:{
      label: '单据编号',
      comp: 'el-input'
    },
    // cInvCode: {
    //   label: '存货信息',
    //   placeholder: '请选择存货',
    //   comp: 't-select',
    //   isSelfCom: true,
    //   bind: {
    //     valueCustom: 'id',
    //     labelCustom: 'name',
    //     optionSource: state.invOptions
    //   }
    // },
    cCusCode: {
      label: '客户',
      comp: 't-select',
      isSelfCom: true,
      bind: {
        valueCustom: 'cCusCode',
        labelCustom: 'ccusname',
        optionSource: cubasdoc.data
      }
    },
    StateID: {
      label: '单据状态',
      comp: 't-select',
      isSelfCom: true,
      bind: {
        valueCustom: 'value',
        labelCustom: 'label',
        optionSource: [
          {
            label: '已审核',
            value: '已审核'
          },
          {
            label: '自由',
            value: '自由'
          },
          {
            label: '提交中',
            value: '提交中'
          },
          {
            label: '系统自动',
            value: '系统自动'
          },
        ]
      }
    },

    salesman: {
      label: '业务员',
      comp: 't-select',
      isSelfCom: true,
      bind: {
        valueCustom: 'cPsn_Num',
        labelCustom: 'cPsn_Name',
        optionSource: state.userList
      }
    },
    dbdate: {
      label: '制单时间',
      comp: 'el-date-picker',
      span: 1,
      event: 'date',
      bind: {
        rangeSeparator: '-',
        startPlaceholder: '开始日期',
        endPlaceholder: '结束日期',
        valueFormat: 'YYYY-MM-DD',
        type: 'daterange'
      }
    },
    FHZX: {
      label: '执行情况',
      comp: 't-select',
      isSelfCom: true,
      bind: {
        valueCustom: 'value',
        labelCustom: 'label',
        optionSource: [
          {
            label: '发货已完成',
            value: '发货已完成'
          },
          {
            label: '发货未完成',
            value: '发货未完成'
          }
        ]
      }
    }
  }
})
// 最终参数获取
const getQueryData = computed(() => {
  let queryList = []
  const res = toRefs(state.queryData)
  Object.keys(res).forEach(item => {

    let data = {}
    if (res[item].value) {
      if (item === 'dbdate') {
        data = {
          field:'Pdate',
          op:'and',
          value:res[item].value[0],
          type:'date'
        }
        queryList.push(data)
        data = {
          field:'Pdateend',
          op:'and',
          value:res[item].value[1],
          type:'date'
        }
        queryList.push(data)
      } else {
        data = {
          field:item,
          op:'and',
          value:res[item].value,
          type:'text'
        }
        queryList.push(data)
      }
    }
  })
  return queryList.length > 0 ? { rules:queryList,op:"and" }:null
})
// 点击查询按钮
const conditionEnter = (data: any) => {

  state.queryData = data
  getData()
}
onMounted(() => {

  getUserList()
  getInvList()
  findContracts()
  initRoleList()
  getData()
})
// 获取菜单数据
const getData = async () => {

  let queryData = {
    table: 'SalesChangeOrderView',
    // name: "undefined",
    name: 'cDepName like',
    value: '销售',
    // value: "undefined",
    DoType: 0,
    KJTJ: ''
  }
  if (getQueryData.value) {
    queryData.KJTJ = JSON.stringify(getQueryData.value)
  }
  const formData = new FormData()
  formData.append('page', state.table.currentPage) // 添加字段
  formData.append('pagesize', state.table.pageSize) // 添加另一个字段

  const { Rows,Total } = await salesOrderChangeList(queryData, formData)
  if (Rows.length>0) {
    state.table.data = Rows
    state.table.total = Total
  }
}
// 页面大小
const handlesSizeChange = (val: any) => {
  state.table.pageSize = val
  getData()
}
// 页码
const handlesCurrentChange = (val: any) => {
  state.table.currentPage = val
  getData()
}

//打开新增窗口
function addHandle() {
  state.addDialog.visible = true
}
//关闭弹窗
function closeDialog() {
  state.addDialog.visible = false
  state.update.visible = false
}

//校验表单需要定义ref
let formRef = ref({})
const singleEditTSelectTable: any = ref(null)
//提交数据
const submitForm = debounce(
  async () => {
    state.loading = true

    // state.addDialog.formData.Sid=null
    // state.addDialog.formData.StateID='自由'
    formRef.value.validate(async vaild => {
      if (vaild) {
        `singleEditTSelectTable`.value.saveMethod(async data => {

          // 提交表单
          let subData = {
            HeaderJson: [state.addDialog.formData],
            BodyJson: data
          }
          const res = await salesOrderAdd({ list: subData })
          if (res.code === 1) {
            ElNotification.error({
              title: '提示',
              message: res.news,
              offset: 200,
            })
            closeDialog()
            await getData()
          }
        })
        state.loading = false
      }
      state.loading = false
    })
  },
  false,
  1000
)


let updateformRef = ref({})
const singleUpdateTSelectTable: any = ref(null)
const submituUpdateForm = debounce(
  async () => {
   // state.loading = true

    // state.update.formData.Sid=null
    closeDialog()
  },
  false,
  1000
)



//客户选择
function changeCustCode(e) {
  //过滤客户
  let cusoptions = cubasdoc.data.filter(its => {
    return its.cCusCode.toLowerCase().includes(e.toLowerCase())
  })[0]

  if (cusoptions) {
    //赋值
    state.addDialog.formData.address = cusoptions.ccusAddress
  }
}

const cubasdoc = cubasdocStore()
//选择项
const cusoptions = ref(cubasdoc.data)
const cnvbasdocMethod = query => {
  if (query) {
    state.loading = true
    setTimeout(() => {
      state.loading = false

      cusoptions.value = cubasdoc.data.filter(its => {
        return (
          its.cCusCode.toLowerCase().includes(query.toLowerCase()) ||
          its.ccusabbname.toLowerCase().includes(query.toLowerCase())
        )
      })
    }, 200)
  } else {
    cusoptions.value = cubasdoc.data
  }
}

// 编辑单元格监听事件
const handleEvent = (type, val, index) => {

}

// 错误校验提示
const validateError = list => {
  list.map(val => {
    setTimeout(() => {
      ElNotification.error({
        title: '提示',
        message: `${val}是必填项！`,
        offset: 200,
      })
    }, 100)
  })
}

function addOneTable() {
  state.table_d.data.push({
    //获取最大行号加1
    // LineNum: state.table.data.length + 1,
  })
}

//查询存货 -- 增加防抖函数
const remoteMethod = debounce(
  async query => {
    if (query) {
      state.loading = true
      state.loading = false

      let invData = {
        Code: query
      }
      //let { Data } = await GetInventory2(invData)
      //state.invList = Data
      state.options = state.invList.filter(item => {
        return (
          item.name.toLowerCase().includes(query.toLowerCase()) ||
          item.id.toLowerCase().includes(query.toLowerCase())
        )
      })
    } else {
      state.options = state.invList
    }
  },
  200,
  false
)

//存货选择
async function updateInv(e, row) {

  //过滤客户
  let invoptions = state.invList.filter(its => {
    return its.id.toLowerCase().includes(e.toLowerCase())
  })[0]
  if (invoptions) {
    //赋值
    row.cInvName = invoptions.name

    //row.Unit = invoptions.cComUnitCode 05191025  D080000141
  }
  //let response = await findListwldza({ cInvCode: e, cCusCode: state.addDialog.formData.CustCode })

}

//获取人员档案
const getUserList = async () => {
  let data = {
    page: 1,
    pagesize: 100000
  }
  let sqlString = {
    sqlString:
      'select cPsn_Name,cPsn_Num,cDept_num,cDepName from hr_hi_person p left join Department d on p.cDept_num = d.cDepCode'
  }

  let { Rows } = await findbaseBasicManage(data, sqlString)

  state.userList = Rows

}

function changeSalesman(e) {
  //过滤客户
  let useroptions = state.userList.filter(its =>
    its.cPsn_Num.toLowerCase().includes(e.toLowerCase())
  )
  if (useroptions) {
    //赋值
    state.addDialog.formData.cDepName = useroptions[0].cDepName
    state.addDialog.formData.depcode = useroptions[0].cDept_num
  }
}

//查询存货信息
const getInvList = async () => {
  let Rows = await findBoxData()
  state.invList = Rows


  state.invOptions = await ComboBoxDataList()
}

// 数量change事件
const numChange = (val, prop, scope) => {
  // let rate = (state.clumTable.data[scope.$index].Rate /100) + 1
  //
  // state.clumTable.data[scope.$index].Amount= (Number(state.clumTable.data[scope.$index].quantity || 0) * Number(state.clumTable.data[scope.$index].UnitPrice || 0)).toFixed(2)//含税金额
  // state.clumTable.data[scope.$index].UnitPrice=(Number(state.clumTable.data[scope.$index].Price || 0) / rate).toFixed(5)//不含税单价=含税单价 / 1.13
}

const updateChangeContent = (val, prop, scope) => {

  //将变更字段加入到ChangeContent，形成逗号字符串
  let split = state.table_u.data[scope.$index].ChangeContent?.split(',')
  if (!split.includes(scope.column.label)){
    state.table_u.data[scope.$index].ChangeContent = state.table_u.data[scope.$index].ChangeContent + scope.column.label + ','
  }
  //计算变更字段
    //发货日期变化
  if (prop === 'deliverDate'){
    //计算YDeliveryDate 与 DeliveryDate 时间相差天数
    let s = parseTime(val, '{y}-{m}-{d}')


    let number = dateDiff(parseTime(val, '{y}-{m}-{d}'), parseTime(state.table_u.data[scope.$index].YdeliverDate, '{y}-{m}-{d}'))
    let days = Math.abs(number);//取绝对值
    if (number>0){
      state.table_u.data[scope.$index].DateChange = '提前'+days + '天'
    }else {
      state.table_u.data[scope.$index].DateChange = '延后'+days + '天'
    }

  }

}

function updateContarctInfo(e) {
  //查询过滤合同信息
  let contractInfo = cubasdoc.contractList.find(item => item.ContractNum === e)
  if (contractInfo) {
    //赋值
    state.addDialog.formData.cCusCode = contractInfo?.CustCode
    state.addDialog.formData.address = contractInfo?.CustAdd
    state.addDialog.formData.cCusName =contractInfo?.CustName

    state.addDialog.formData.taxrate = contractInfo?.Rate

    //调用查询合同详细信息
    findContractInfo(contractInfo.Id)
  }
}

//查询合同详细信息
async function findContractInfo(id) {
  let { Data } = await getContractInfo({ id: id })
  if (Data?.SubList2) {
    //赋值合同明细
    state.table_d.data = Data.SubList2.map(item => {
      return {
        cInvName: item.CinvName,
        cInvCode: item.CinvCode,
        cInvStd: item.CinvAdd,

        quantity: item.Quantity,
        UnitPrice: item.Price,
        ContractID: item.Id,
        ContractNo: Data.Main.ContractNum,
        taxRate: Data.Main.Rate,
        // deliver:parseTime(new Date(), "{y}-{m}-{d} {h}:{i}:{s}"),
        //deliverDate:"2024-08-15T16:00:00.000Z",
        // MaterialShutdown:"1753-01-01 00:00:00",
        // DeliveryTime:"1753-01-01 00:00:00",
        upgrade: '是'
      }
    })

  }
}

//查询合同信息
async function findContracts() {
  let queryData = {
    ContractType: null,
    CustCode: null,
    CustName: null,
    ContractNum: null,
    CreateFrom: null,
    CreateTo: null,
    Type: null,
    CreateBy: null
  }
  //获取合同信息
  let contractData = await getContractList(queryData)
  cubasdoc.setContractList(contractData.Data)
}

const initRoleList = async () => {
  let res = await userRole({ VT_ID: '合销售变更单' })
  state.roleList = res.items
}
</script>
<style lang="scss" scoped>
.dialog-footer{

}
</style>
